package bb.lanxing.lib.devices.ble.device;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.base.SimpleBluetoothGattCallbackCompat;
import bb.lanxing.lib.devices.core.ble.AbsBleDevice;
import bb.lanxing.lib.devices.core.provider.DataNotifier;
import java.util.UUID;

public class StandardHeartrateDevice extends AbsBleDevice {
    public static final UUID BLE_HEART_RATE_SERVICE = UUID.fromString("0000180d-0000-1000-8000-00805f9b34fb");
    public static final UUID BLE_HEART_RATE_MEASUREMENT = UUID.fromString("00002a37-0000-1000-8000-00805f9b34fb");

    public StandardHeartrateDevice(Context context, SmartDevice smartDevice) {
        super(smartDevice);
        init(context, smartDevice.getAddress(), new HeartateBluetoothGattCallback(this));
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onServicesDiscovered() {
        super.onServicesDiscovered();
        BluetoothGattCharacteristic characteristic = mBluetoothGatt.getService(BLE_HEART_RATE_SERVICE).getCharacteristic(BLE_HEART_RATE_MEASUREMENT);
        mBluetoothGatt.readCharacteristic(characteristic);
        setCharacteristicNotification(characteristic, true);
    }

    private static class HeartateBluetoothGattCallback extends SimpleBluetoothGattCallbackCompat<StandardHeartrateDevice> {
        HeartateBluetoothGattCallback(StandardHeartrateDevice standardHeartrateDevice) {
            super(standardHeartrateDevice);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
            int intValue;
            super.onCharacteristicChanged(bluetoothGatt, bluetoothGattCharacteristic);
            UUID uuid = bluetoothGattCharacteristic.getUuid();
            int type = this.mClientRef.getType();
            if (StandardHeartrateDevice.BLE_HEART_RATE_MEASUREMENT.equals(uuid)) {
                if ((bluetoothGattCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0) & 1) == 0) {
                    intValue = bluetoothGattCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1);
                } else {
                    intValue = bluetoothGattCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 1);
                }
                DataNotifier.notifyHeartrateData(type, this.mClientRef.getAddress(), intValue);
            }
        }
    }
}
